package com.intramirror.product.service.impl;

import com.intramirror.product.entity.*;
import com.intramirror.product.enums.PriceChangeRuleEnum;
import com.intramirror.product.exception.BusinessException;
import com.intramirror.product.mapper.*;
import com.intramirror.product.service.IPriceRuleService;
import com.intramirror.product.utils.ConvertUtil;
import com.intramirror.product.utils.DateUtils;
import com.intramirror.product.vo.BasePriceRuleChangeVO;
import com.intramirror.product.vo.BrandCategoryPriceChangeRuleVO;
import com.intramirror.utils.transform.JsonTransformUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

@Service
public class PriceRuleServiceImpl implements IPriceRuleService {
    private static final Logger LOGGER = LoggerFactory.getLogger(PriceRuleServiceImpl.class);

    @Autowired
    ImPriceAlgorithmRuleMapper imPriceAlgorithmRuleMapper;

    @Autowired
    ImPriceAlgorithmRuleBrandMapper imPriceAlgorithmRuleBrandMapper;

    @Autowired
    ImPriceDiscountMappingMapper imPriceDiscountMappingMapper;

    @Autowired
    PriceChangeRuleMapper priceChangeRuleMapper;

    @Autowired
    SnapshotPriceDetailMapper snapshotPriceDetailMapper;

    @Autowired
    SnapshotPriceRuleMapper snapshotPriceRuleMapper;

    @Override
    public Map<Long, List<ImPriceDiscountMapping>> getImBrandRuleMapping(Long imPriceAlgorithmId) {
        Map<Long, List<ImPriceDiscountMapping>> result = new HashMap<>();
        List<ImPriceAlgorithmRule> imPriceAlgorithmRules = imPriceAlgorithmRuleMapper.getImPriceAlgorithmRuleByAlgorithmId(imPriceAlgorithmId);
        for (ImPriceAlgorithmRule imPriceAlgorithmRule : imPriceAlgorithmRules) {
            List<ImPriceAlgorithmRuleBrand> listRuleBrand = getImPriceRuleBrand(imPriceAlgorithmRule.getImPriceAlgorithmRuleId());
            List<ImPriceDiscountMapping> listDiscountMapping = getDiscountMappingByRule(imPriceAlgorithmRule.getImPriceAlgorithmRuleId());

            if (listRuleBrand != null && listDiscountMapping != null && listRuleBrand.size() > 0 && listDiscountMapping.size() > 0) {
                for (ImPriceAlgorithmRuleBrand ruleBrand : listRuleBrand) {
                    LOGGER.debug("Get discount mapping for brand {}.", ruleBrand.getBrandId());
                    result.put(ruleBrand.getBrandId(), listDiscountMapping);
                }
            }
        }
        return result;
    }

    public Map<Long, List<ImPriceDiscountMapping>> getHotImBrandRuleMapping() {
        Map<Long, List<ImPriceDiscountMapping>> result = new HashMap<>();
        List<ImPriceAlgorithmRule> imPriceAlgorithmRules = imPriceAlgorithmRuleMapper.getHotImPriceAlgorithmRule();
        for (ImPriceAlgorithmRule imPriceAlgorithmRule : imPriceAlgorithmRules) {
            List<ImPriceAlgorithmRuleBrand> listRuleBrand = getImPriceRuleBrand(imPriceAlgorithmRule.getImPriceAlgorithmRuleId());
            List<ImPriceDiscountMapping> listDiscountMapping = getDiscountMappingByRule(imPriceAlgorithmRule.getImPriceAlgorithmRuleId());

            if (listRuleBrand != null && listDiscountMapping != null && listRuleBrand.size() > 0 && listDiscountMapping.size() > 0) {
                for (ImPriceAlgorithmRuleBrand ruleBrand : listRuleBrand) {
                    LOGGER.debug("Get discount mapping for hot brand {}.", ruleBrand.getBrandId());
                    result.put(ruleBrand.getBrandId(), listDiscountMapping);
                }
            }
        }
        return result;
    }

    /**
     * 计算所有使用了改算法的 price rule, 将计算结果同步到snapshot_price_detail
     * @param imPriceAlgorithmId
     *         算法Id
     */
    @Transactional
    @Override
    public void refreshSnapshotPrice(Long imPriceAlgorithmId) throws Exception {
        LOGGER.info("Start to refresh algorithm {}.", imPriceAlgorithmId);
        Map<Long, Map<Integer, Integer>> brandDiscountMapping = convertDiscountMapping(getImBrandRuleMapping(imPriceAlgorithmId));
        Map<Long, Map<Integer, Integer>> hotBrandDiscountMapping = convertDiscountMapping(getHotImBrandRuleMapping());

        List<Map<String, Object>> priceChangeRuleList = priceChangeRuleMapper.getSnapshotPriceRuleByAlgorithm(imPriceAlgorithmId);
        for (Map<String, Object> priceChangeRule : priceChangeRuleList) {
            refreshSnapshotPriceForRule(brandDiscountMapping, hotBrandDiscountMapping, ConvertUtil.toLong(priceChangeRule.get("price_change_rule_id")),
                    ConvertUtil.toLong(priceChangeRule.get("snapshot_price_rule_id")), ConvertUtil.toInteger(priceChangeRule.get("category_type")));

            if (ConvertUtil.toInteger(priceChangeRule.get("preview_status")) == 1 && ConvertUtil.toInteger(priceChangeRule.get("status")) == 1) {
                // need refresh
                updateProductPreviewPriceByBoutique(ConvertUtil.toLong(priceChangeRule.get("price_change_rule_id")), 1, 0);
            }

            if (ConvertUtil.toInteger(priceChangeRule.get("status")) == 2) {
                List<Long> ruleIds = new ArrayList<>();
                ruleIds.add(ConvertUtil.toLong(priceChangeRule.get("price_change_rule_id")));
                synUpdateProductPriceByPriceChangeRuleIds(ruleIds);
            }
        }
    }

    @Transactional
    @Override
    public void refreshSnapshotPrice(Long imPriceAlgorithmId, Long ruleId) throws Exception {
        LOGGER.info("Start to refresh algorithm {}, priceRule {}.", imPriceAlgorithmId, ruleId);
        Map<Long, Map<Integer, Integer>> brandDiscountMapping = convertDiscountMapping(getImBrandRuleMapping(imPriceAlgorithmId));
        Map<Long, Map<Integer, Integer>> hotBrandDiscountMapping = convertDiscountMapping(getHotImBrandRuleMapping());

        List<Map<String, Object>> priceChangeRuleList = priceChangeRuleMapper.getSnapshotPriceRuleByAlgorithm(imPriceAlgorithmId);
        for (Map<String, Object> priceChangeRule : priceChangeRuleList) {
            if (ConvertUtil.toLong(priceChangeRule.get("price_change_rule_id")).longValue() == ruleId) {
                refreshSnapshotPriceForRule(brandDiscountMapping, hotBrandDiscountMapping, ConvertUtil.toLong(priceChangeRule.get("price_change_rule_id")),
                        ConvertUtil.toLong(priceChangeRule.get("snapshot_price_rule_id")), ConvertUtil.toInteger(priceChangeRule.get("category_type")));

                if (ConvertUtil.toInteger(priceChangeRule.get("preview_status")) == 1 && ConvertUtil.toInteger(priceChangeRule.get("status")) == 1) {
                    // need refresh
                    updateProductPreviewPriceByBoutique(ruleId, 1, 0);
                }

                if (ConvertUtil.toInteger(priceChangeRule.get("status")) == 2) {
                    List<Long> ruleIds = new ArrayList<>();
                    ruleIds.add(ruleId);
                    synUpdateProductPriceByPriceChangeRuleIds(ruleIds);
                }
            }
        }
    }

    @Override
    public void changePriceRule(BasePriceRuleChangeVO basePriceRuleChangeVO) {
        // todo
        if (basePriceRuleChangeVO.getType() == 3 || basePriceRuleChangeVO.getType() == 4 || basePriceRuleChangeVO.getType() == 5) {
            brandCategoryPriceRuleChange((BrandCategoryPriceChangeRuleVO) basePriceRuleChangeVO);
        }
    }

    // not finish
    private void brandCategoryPriceRuleChange(BrandCategoryPriceChangeRuleVO brandCategoryPriceChangeRuleVO) {
        Map<String, Object> priceChangeRule = priceChangeRuleMapper.getSnapshotPriceRuleByRuleId(brandCategoryPriceChangeRuleVO.getPriceChangeRuleId());
        Long algorithmId = ConvertUtil.toLong(priceChangeRule.get("im_price_algorithm_id"));
        Long snapshotRuleId = ConvertUtil.toLong(priceChangeRule.get("snapshot_price_rule_id"));
        brandCategoryPriceChangeRuleVO.setSnapshotRuleId(snapshotRuleId);

        List<Map<String, Object>> products = null;
        if (brandCategoryPriceChangeRuleVO.getType() == 3) {
            products = priceChangeRuleMapper.getProductSubCategoryBrandChangeRule(brandCategoryPriceChangeRuleVO);
        } else if (brandCategoryPriceChangeRuleVO.getType() == 4) {
            products = priceChangeRuleMapper.getProductCategoryBrandChangeRule(brandCategoryPriceChangeRuleVO);
        } else if (brandCategoryPriceChangeRuleVO.getType() == 5) {
            products = priceChangeRuleMapper.getProductDefaultCategoryBrandChangeRule(brandCategoryPriceChangeRuleVO);
        }

        LOGGER.info("Start change snapshot {} algorithm {}, priceRule {}.", snapshotRuleId, algorithmId, brandCategoryPriceChangeRuleVO.getPriceChangeRuleId());
        Map<Long, List<ImPriceDiscountMapping>> mapBrandMapping = getImBrandRuleMapping(algorithmId);
        Map<Long, Map<Integer, Integer>> brandDiscountMapping = convertDiscountMapping(mapBrandMapping);

        Integer boutiqueDiscount = brandCategoryPriceChangeRuleVO.getBoutiqueDiscount();
        Integer defaultImDiscount = ConvertUtil.toInteger(priceChangeRuleMapper.getSystemDefaultDiscount());
        Integer imDiscount = getImDiscount(brandCategoryPriceChangeRuleVO.getBrandId(), Long.valueOf(boutiqueDiscount), brandDiscountMapping);
        if (imDiscount == null) {
            imDiscount = defaultImDiscount;
        }

        List<SnapshotPriceDetail> updateRecords = new ArrayList<>();
        for (Map<String, Object> row : products) {
            SnapshotPriceDetail record = new SnapshotPriceDetail();
            record.setSnapshotPriceRuleId(snapshotRuleId);
            record.setBoutiqueDiscountOff(boutiqueDiscount);
            record.setImDiscountOff(imDiscount);
            record.setProductId(ConvertUtil.toLong(row.get("product_id")));
            record.setType(Byte.valueOf(String.valueOf(brandCategoryPriceChangeRuleVO.getType())));

            BigDecimal retailPrice = ConvertUtil.toBigDecimal(row.get("retail_price"));
            record.setRetailPrice(retailPrice);
            BigDecimal boutiquePrice = retailPrice.multiply(new BigDecimal(boutiqueDiscount)).divide(new BigDecimal(122), 2, RoundingMode.HALF_UP);
            BigDecimal imPrice = retailPrice.multiply(new BigDecimal(imDiscount)).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
            record.setBoutiquePrice(boutiquePrice);
            record.setImPrice(imPrice);
            updateRecords.add(record);
        }

        // 1 update
        snapshotPriceDetailMapper.batchUpdate(updateRecords, snapshotRuleId);
        // 2 insert

    }

    /**
     * 计算单个 price rule 对应的价格
     * @param mapBrandMapping
     *         算法
     * @param priceRuleId
     *         priceRuleId
     */
    private void refreshSnapshotPriceForRule(Map<Long, Map<Integer, Integer>> mapBrandMapping, Map<Long, Map<Integer, Integer>> mapHotBrandMapping,
            Long priceRuleId, Long snapshotRuleId, Integer categoryType) {
        snapshotPriceDetailMapper.deleteSnapshotDetailBySnapshotRuleId(snapshotRuleId);

        // update snapshot rule updated_at
        SnapshotPriceRule snapshotPriceRule = new SnapshotPriceRule();
        snapshotPriceRule.setSnapshotPriceRuleId(snapshotRuleId);
        snapshotPriceRule.setUpdatedAt(new Date());
        snapshotPriceRuleMapper.updateByPrimaryKeySelective(snapshotPriceRule);

        LOGGER.info("Start to calculate im price discount for price rule {}.", priceRuleId);
        List<Map<String, Object>> priceChangeRuleProductList = priceChangeRuleMapper.getProductPriceChangeRule(priceRuleId, snapshotRuleId, categoryType);
        calculateImDiscount(mapBrandMapping, mapHotBrandMapping, priceChangeRuleProductList, snapshotRuleId, 1);

        List<Map<String, Object>> priceChangeRuleGroupList = priceChangeRuleMapper.getProductGroupPriceChangeRule(priceRuleId, snapshotRuleId, categoryType);
        calculateImDiscount(mapBrandMapping, mapHotBrandMapping, priceChangeRuleGroupList, snapshotRuleId, 2);

        List<Map<String, Object>> priceChangeRuleSubCategoryBrandList = priceChangeRuleMapper.getSubCategoryBrandChangeRule(priceRuleId, snapshotRuleId);
        calculateImDiscount(mapBrandMapping, mapHotBrandMapping, priceChangeRuleSubCategoryBrandList, snapshotRuleId, 3);

        List<Map<String, Object>> priceChangeRuleCategoryBrandList = priceChangeRuleMapper.getCategoryBrandChangeRule(priceRuleId, snapshotRuleId);
        calculateImDiscount(mapBrandMapping, mapHotBrandMapping, priceChangeRuleCategoryBrandList, snapshotRuleId, 4);

        List<Map<String, Object>> priceChangeRuleDefaultCategoryBrandList = priceChangeRuleMapper.getDefaultCategoryBrandChangeRule(priceRuleId,
                snapshotRuleId);
        calculateImDiscount(mapBrandMapping, mapHotBrandMapping, priceChangeRuleDefaultCategoryBrandList, snapshotRuleId, 5);
    }

    private void calculateImDiscount(Map<Long, Map<Integer, Integer>> mapBrandMapping, Map<Long, Map<Integer, Integer>> mapHotBrandMapping,
            List<Map<String, Object>> priceChangeRuleProductList, Long snapshotRuleId, int type) {
        Integer defaultImDiscount = ConvertUtil.toInteger(priceChangeRuleMapper.getSystemDefaultDiscount());
        List<SnapshotPriceDetail> records = new ArrayList<>();
        for (Map<String, Object> row : priceChangeRuleProductList) {
            Long brandId = ConvertUtil.toLong(row.get("brand_id"));
            Long boutiqueDiscount = ConvertUtil.toLong(row.get("discount_percentage"));

            Integer imDiscount;

            if (row.get("tag_product_id") == null) {
                imDiscount = getImDiscount(brandId, boutiqueDiscount, mapBrandMapping);
            } else {
                // 爆款
                imDiscount = getImDiscount(brandId, boutiqueDiscount, mapHotBrandMapping);
            }

            if (imDiscount == null) {
                imDiscount = defaultImDiscount;
            }

            SnapshotPriceDetail record = new SnapshotPriceDetail();
            record.setSnapshotPriceRuleId(snapshotRuleId);
            BigDecimal retailPrice = ConvertUtil.toBigDecimal(row.get("retail_price"));
            record.setRetailPrice(retailPrice);
            record.setBoutiqueDiscountOff(boutiqueDiscount.intValue());
            record.setImDiscountOff(imDiscount);
            record.setProductId(ConvertUtil.toLong(row.get("product_id")));
            record.setType(Byte.valueOf(String.valueOf(type)));
            BigDecimal boutiquePrice = retailPrice.multiply(new BigDecimal(boutiqueDiscount)).divide(new BigDecimal(122), 2, RoundingMode.HALF_UP);
            BigDecimal imPrice = retailPrice.multiply(new BigDecimal(imDiscount)).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
            record.setBoutiquePrice(boutiquePrice);
            record.setImPrice(imPrice);
            records.add(record);
        }
        if (records.size() > 0) {
            LOGGER.info("Start to batch insert, records size is {}.", records.size());
            snapshotPriceDetailMapper.batchInsert(records);
        } else {
            LOGGER.info("No product should be insert with type {}.", type);
        }
    }

    /**
     * 获取 brandId 和 boutique discount 对应的 IM discount
     * @param brandId
     *         商品品牌
     * @param boutiqueDiscount
     *         boutique 折扣
     * @param mapBrandMapping
     *         算法规则
     * @return brand和discount匹配的im折扣， null为未匹配到
     */
    public Integer getImDiscount(Long brandId, Long boutiqueDiscount, Map<Long, Map<Integer, Integer>> mapBrandMapping) {

        LOGGER.info("==Jian== getImDiscount：boutiqueDiscount is {}.", boutiqueDiscount);
        LOGGER.info("==Jian== getImDiscount：mapBrandMapping is {}.", mapBrandMapping);
        Map<Integer, Integer> generalMappings = mapBrandMapping.get(-1L);
        if (mapBrandMapping.containsKey(brandId)) {
            Map<Integer, Integer> discountMappings = mapBrandMapping.get(brandId);

            if (!discountMappings.containsKey(ConvertUtil.toInteger(boutiqueDiscount))) {
                return generalMappings.get(ConvertUtil.toInteger(boutiqueDiscount));
            } else {
                return discountMappings.get(ConvertUtil.toInteger(boutiqueDiscount));
            }
        }
        if (generalMappings != null) {
            return generalMappings.get(ConvertUtil.toInteger(boutiqueDiscount));
        }
        return null;
    }

    public Map<Long, Map<Integer, Integer>> convertDiscountMapping(Map<Long, List<ImPriceDiscountMapping>> mapBrandMapping) {
        Map<Long, Map<Integer, Integer>> result = new HashMap<>();
        for (Map.Entry<Long, List<ImPriceDiscountMapping>> entry : mapBrandMapping.entrySet()) {
            Map<Integer, Integer> mapping = new HashMap<>();
            for (ImPriceDiscountMapping imPriceDiscountMapping : entry.getValue()) {
                mapping.put(imPriceDiscountMapping.getBoutiqueDiscountOff(), imPriceDiscountMapping.getImDiscountOff());
            }

            LOGGER.info("Convert discount mappping key {}.", entry.getKey());
            result.put(entry.getKey(), mapping);
        }
        return result;
    }

    private List<ImPriceAlgorithmRuleBrand> getImPriceRuleBrand(Long algorithmRuleId) {
        return imPriceAlgorithmRuleBrandMapper.getAlgorithmRuleBrandByRuleId(algorithmRuleId);
    }

    private List<ImPriceDiscountMapping> getDiscountMappingByRule(Long algorithmRuleId) {
        return imPriceDiscountMappingMapper.getDiscountMappingByRuleId(algorithmRuleId);
    }

    @Transactional
    @Override
    public void updateProductPreviewPriceByBoutique(Long ruleId, Integer previewStatus, int f) {
        PriceChangeRule pcrModel = priceChangeRuleMapper.selectByPrimaryKey(ruleId);
        String flag = "";
        if (f == 1) {
            flag = "all";
        }
        if (flag.equalsIgnoreCase("all")) {
            ruleId = null;
        }

        if (pcrModel != null) {
            pcrModel.setPriceChangeRuleId(ruleId);
            pcrModel.setPreviewStatus(previewStatus);

            priceChangeRuleMapper.updatePriceChangeRuleById(pcrModel);//preview_status
            priceChangeRuleMapper.updateProductImPriceByConditions(pcrModel);//preview_im_price
        }
    }

    @Override
    public PriceChangeRule selectByPrimaryKey(Long priceChangeRuleId) {
        return priceChangeRuleMapper.selectByPrimaryKey(priceChangeRuleId);
    }

    @Override
    public boolean synUpdateProductPrice(Long vendor_id, int categoryType, Long price_change_rule_id) throws Exception {
        synchronized (this) {
            LOGGER.info("updateVendorPrice start");
            Map<String, Object> paramsMap = new HashMap<>();
            paramsMap.put("price_type", PriceChangeRuleEnum.PriceType.SUPPLY_PRICE.getCode());
            paramsMap.put("preview_status", "1");
            paramsMap.put("vendor_id", vendor_id);
            paramsMap.put("category_type", categoryType);
            paramsMap.put("price_change_rule_id", price_change_rule_id);
            List<Map<String, Object>> selSeasonGroupRuleMaps = priceChangeRuleMapper.selectSeasonGroupRule(paramsMap);
            for (Map<String, Object> selSeasonGroupRuleMap : selSeasonGroupRuleMaps) {
                if (selSeasonGroupRuleMap.get("im_price_algorithm_id") == null) {
                    LOGGER.info("Start running IM discounts Error,price_change_rule_id {}", selSeasonGroupRuleMap.get("price_change_rule_id"));
                    throw new BusinessException("不允许执行未设置Im Price Algorithm的Boutique折扣。");
                }
            }
            updatePrice(selSeasonGroupRuleMaps);
            this.updateRuleStatus(paramsMap);
            return true;
        }
    }

    @Override
    public boolean synUpdateProductPriceByValidFrom(String startTime, String endTime) throws Exception {
        synchronized (this) {
            LOGGER.info("updateVendorPrice start");
            Map<String, Object> paramsMap = new HashMap<>();
            paramsMap.put("price_type", PriceChangeRuleEnum.PriceType.SUPPLY_PRICE.getCode());
            paramsMap.put("preview_status", "0");
            paramsMap.put("startTime", startTime);
            paramsMap.put("endTime", endTime);
            List<Map<String, Object>> selSeasonGroupRuleMaps = priceChangeRuleMapper.selectSeasonGroupRule(paramsMap);

            updatePrice(selSeasonGroupRuleMaps);
            this.updateRuleStatus(paramsMap);
            return true;
        }
    }

    private void updatePrice(List<Map<String, Object>> selSeasonGroupRuleMaps) throws BusinessException {
        List<Long> priceChangeRuleIdList = new ArrayList<>();

        if (selSeasonGroupRuleMaps != null && selSeasonGroupRuleMaps.size() > 0) {
            for (Map<String, Object> selSeasonGroupRuleMap : selSeasonGroupRuleMaps) {
                priceChangeRuleIdList.add(Long.parseLong(selSeasonGroupRuleMap.get("price_change_rule_id").toString()));
            }
            Map<String, Object> snapshotPriceRuleParams = new HashMap<>();
            snapshotPriceRuleParams.put("priceChangeRuleIdList", priceChangeRuleIdList);
            List<SnapshotPriceRule> snapshotPriceRules = snapshotPriceRuleMapper.getSnapshotPriceRuleByPriceChangeRuleIds(snapshotPriceRuleParams);
            List<Long> snapshotPriceRuleIdList = new ArrayList<>();
            for (SnapshotPriceRule snapshotPriceRule : snapshotPriceRules) {
                if (snapshotPriceRule.getUpdatedAt() == null || snapshotPriceRule.getSaveAt().after(snapshotPriceRule.getUpdatedAt())) {
                    LOGGER.info("snapshotPriceRule SaveAt > UpdatedAt,snapshotPriceRuleId:{}", snapshotPriceRule.getSnapshotPriceRuleId());
                    throw new BusinessException("Active fail. Unrefreshed data Exists.");
                }
                snapshotPriceRuleIdList.add(snapshotPriceRule.getSnapshotPriceRuleId());
            }
            Map<String, Object> params = new HashMap<>();
            params.put("snapshotPriceRuleIdList", snapshotPriceRuleIdList);
            LOGGER.info("synUpdateSkuPriceBySnapshot,params:{}", JsonTransformUtil.toJson(params));
            priceChangeRuleMapper.updateSkuPriceBySnapshot(params);
            LOGGER.info("synUpdateShopProductPriceBySnapshot,params:{}", JsonTransformUtil.toJson(params));
            priceChangeRuleMapper.updateShopProductPriceBySnapshot(params);
            LOGGER.info("synUpdateProductPriceBySnapshot,params:{}", JsonTransformUtil.toJson(params));
            priceChangeRuleMapper.updateProductPriceBySnapshot(params);
            LOGGER.info("synUpdateProductPrice is end");
        }
    }

    private boolean updateRuleStatus(Map<String, Object> params) {
        List<Map<String, Object>> selNowRuleMaps = priceChangeRuleMapper.selNowRule(params);
        params.put("now", DateUtils.getformatDate(new Date()));
        if (selNowRuleMaps != null && selNowRuleMaps.size() > 0) {
            for (Map<String, Object> map : selNowRuleMaps) {
                params.put("vendor_id", map.get("vendor_id"));
                params.put("price_change_rule_id", map.get("price_change_rule_id"));
                params.put("category_type", map.get("category_type"));
                priceChangeRuleMapper.updateRuleInActive(params);
            }

            for (Map<String, Object> map : selNowRuleMaps) {
                params.put("price_change_rule_id", map.get("price_change_rule_id"));
                params.put("category_type", map.get("category_type"));
                priceChangeRuleMapper.updateRuleActive(params);
            }
        }
        return true;
    }

    @Override
    public List<Map<String, Object>> selectNowActiveRule(Map<String, Object> params) {
        return priceChangeRuleMapper.selectNowActiveRule(params);
    }

    @Override
    public boolean synUpdateProductPriceByPriceChangeRuleIds(List<Long> priceChangeRuleIds) throws Exception {
        synchronized (this) {
            LOGGER.info("synUpdateProductPriceByPriceChangeRuleIds start. params={}", priceChangeRuleIds);
            Map<String, Object> paramsMap = new HashMap<>();
            paramsMap.put("priceChangeRuleIds", priceChangeRuleIds);
            List<Map<String, Object>> selSeasonGroupRuleMaps = priceChangeRuleMapper.selectSeasonGroupRuleByPriceChangeRuleIds(paramsMap);

            updatePrice(selSeasonGroupRuleMaps);
            this.updateRuleStatus(paramsMap);
            LOGGER.info("synUpdateProductPriceByPriceChangeRuleIds end.");
            return true;
        }
    }
}
